package com.xw.base.config;

import com.xw.base.entity.base.JsonResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 尝试包装一下返回的结果
 *
 * @author： XW -> ~
 * @create： 2023/11/16 11:35
 */
@RestControllerAdvice(basePackages = "com.shang.bo.ks")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果不需要进行封装的，可以添加一些校验手段，比如添加标记排除的注解
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 提供一定的灵活度，如果body已经被包装了，就不进行包装
        if (body instanceof JsonResult) {
            return body;
        }
        // 如果返回值是String类型，那就手动把Result对象转换成JSON字符串
//        if (body instanceof String) {
//            return JSON.toJSONString(JsonResult.success(body));
//        }
        String requestId = "";


        return new JsonResult<>(0, "success", requestId, body);

    }

}
